<template>
  <div class="qualityAddBox">
    <div>
      <el-card class="card center">
        <el-form
          ref="formAddRef1"
          style="width: 400px"
          :model="formAdd"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
        >
          <el-form-item label="收货门店" prop="storeId">
            <el-select @change="selectStoreFn" v-model="formAdd.storeId" placeholder="请选择门店">
              <el-option
                v-for="item in optionsStore"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="选择表格" prop="storeId">
            <el-button @click="upXlsFn">点击上传</el-button>
            <input
              style="display: none"
              className="upFelis"
              type="file"
              id="excelFile"
              accept=".xlsx, .xls"
            />
          </el-form-item>
          <el-form-item label="选择表格" prop="storeId">
            <el-button @click="onFinish">确定发货</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="card center">
        <el-form
          ref="formAddRef2"
          style="max-width: 400px"
          :model="formAdd"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
        >
          <el-form-item label="客服编号" prop="customerService">
            <el-input placeholder="请输入客服编号" v-model="formAdd.customerService" />
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="card2">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column prop="filmType" label="产品名称" />
          <el-table-column prop="filmId2" label="切分日期" />
          <el-table-column prop="filmId3" label="切分机长代码" />
          <el-table-column prop="filmId4" label="品检代码" />
          <el-table-column prop="filmId5" label="大卷代码" />
          <el-table-column prop="filmId6" label="小卷序号" />
          <el-table-column prop="filmId3" label="操作">
            <template #default="scope">
              <el-button type="warning" size="small" @click="detilsFn(scope)"> 详情 </el-button>
              <el-button type="danger" size="small" @click="DeleteFn(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-dialog v-model="dialogVisible" width="500">
      <div>
        <div class="aliCenter">
          <div className="ContentTitle">产品类型：</div>
          <div className="ContentSize">{{ detilsData.type }}</div>
        </div>
        <div class="aliCenter">
          <div className="ContentTitle">产品型号：</div>
          <div className="ContentSize">{{ detilsData.name }}</div>
        </div>
        <div class="aliCenter">
          <div className="ContentTitle">产品编号：</div>
          <div className="ContentSize">{{ detilsData.nameNumber }}</div>
        </div>
        <div class="aliCenter">
          <div className="ContentTitle">质保年限：</div>
          <div className="ContentSize">{{ detilsData.age }}</div>
        </div>
        <div class="aliCenter">
          <div className="ContentTitle">总使用次数：</div>
          <div className="ContentSize">{{ detilsData.countAll }}</div>
        </div>
        <div class="aliCenter">
          <div className="ContentTitle">漆面膜使用次数：</div>
          <div className="ContentSize">{{ detilsData.lacquerNumber }}</div>
        </div>
        <div class="aliCenter">
          <div className="ContentTitle">改色膜使用次数：</div>
          <div className="ContentSize">{{ detilsData.colorAlterationNumber }}</div>
        </div>
        <div class="aliCenter">
          <div className="ContentTitle">车顶膜使用次数：</div>
          <div className="ContentSize">{{ detilsData.roofNumber }}</div>
        </div>
        <div class="aliCenter">
          <div className="ContentTitle">太阳膜使用次数：</div>
          <div className="ContentSize">{{ detilsData.sunNumber }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { filmListSelect, filmListSelectExcel } from '@/http/api/film.js'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { getstorelistAll, storeInventoryAdd, storeInventoryAdd2 } from '@/http/api/store.js'
import { numberList, number2List, number3List } from '@/http/api/number.js'
import { ref, reactive, onMounted, defineExpose } from 'vue'
import { provinceQualitNumber } from '@/components/js/addressOptions'
import * as XLSX from 'xlsx'
let formAdd = reactive({})
let optionsStore = ref([])
let dialogVisible = ref(false)
let optionsFilmType = [
  { value: '漆面膜', label: '漆面膜' },
  { value: '改色膜', label: '改色膜' },
  { value: '车顶膜', label: '车顶膜' },
  { value: '太阳膜', label: '太阳膜' }
]
let optionsNumber1 = ref([])
let optionsNumber2 = ref([])
let optionsNumber3 = ref([])
let serFilmNameList = ref([])
const getStoreList = async () => {
  const res = await getstorelistAll({
    status: 1
  })
  optionsStore.value = res.data.res.map((item) => {
    return {
      label: item.name,
      value: item.id,
      country: item.country,
      region: item.region.includes("[") ? JSON.parse(item.region)[0] : item.region.split(',')[0]
    }
  })
}
let tableData = ref([])
const upXlsFn = () => {
  const fileInput = document.getElementById('excelFile')
  fileInput.click()
  fileInput.addEventListener('change', async (e) => {
    const file = e.target.files[0]
    const reader = new FileReader()
    reader.onload = (e) => {
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })

      // 获取第一个工作表
      const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
      // 转换为JSON
      const jsonData = XLSX.utils.sheet_to_json(firstSheet)
      console.log(jsonData)
      tableData.value = jsonData.map((item, index) => {
        let data = {
          key: index,
          code: item.code.toUpperCase(),
          filmType: item.code.substring(0, 2).toUpperCase(),
          filmId2: item.code.substring(2, 8).toUpperCase(),
          filmId3: item.code.substring(8, 10).toUpperCase(),
          filmId4: item.code.substring(10, 12).toUpperCase(),
          filmId5: item.code.substring(13, 14).toUpperCase(),
          filmId6: item.code.substring(15, 18).toUpperCase()
        }
        return data
      })

    }
    reader.readAsArrayBuffer(file)
  })
}
const DeleteFn = (data) => {
  tableData.value = tableData.value.filter((item) => {
    if (item.key != data.row.key) return item
  })
}
const onFinish = async () => {
  let upData = {
    storeId: [formAdd.storeId],
    customerService: formAdd.customerService,
    customerPhone: JSON.parse(localStorage.getItem('userInfo')).phone,
    table: tableData.value,
  }
  const res = await storeInventoryAdd2(upData)
  if (res.data.type == 2) {
    ElMessage.error(res.data.message)
  }
}
let detilsData = reactive({})
const detilsFn = async (data) => {
  dialogVisible.value = true
  let res = await filmListSelectExcel({ nameNumber: data.row.filmType, })
  Object.assign(detilsData, res.data.res)
}
const rules = reactive({
  storeId: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  customerService: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  startNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
  endNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], region: [
    { required: true, message: '请选择', trigger: 'blur' },
  ], filmType: [
    { required: true, message: '请选择', trigger: 'blur' },
  ], filmId: [
    { required: true, message: '请选择', trigger: 'blur' },
  ], filmAge: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], lacquerNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], roofNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], sunNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], colorAlterationNumber: [
    { required: true, message: '请输入', trigger: 'blur' },
  ], count: [
    { required: true, message: '请选择', trigger: 'blur' },
  ],

})
let filmName = ref('')
// 修改选择后重新获取膜列表
const getFilmList = async () => {
  let serchFilm = {
    storeId: formAdd.storeId,
    type: formAdd.filmType
  }
  const res = await filmListSelect(serchFilm)
  serFilmNameList.value = res.data.res.map((item) => {
    return {
      value: item.id,
      label: item.name,
      ...item
    }
  })
  console.log(number1, number2, number3, number4)
  if (formAdd.filmType && filmName.value) {

    let QualityNumber = dayjs().format('YYMMDD')
    formAdd.startNumber = `${number4}${QualityNumber}${number1}${number2}-${number3}-001`
    formAdd.endNumber = `${number4}${QualityNumber}${number1}${number2}-${number3}-`
  }
}
// 选择门店
const selectStoreFn = (data) => {
  console.log(data)
  optionsStore.value.forEach((item) => {
    if (item.value == data) {
      formAdd.region = item.region
    }
  })

}
// 选择膜
const selectFilmName = (data) => {
  console.log(data)
  serFilmNameList.value.forEach((item) => {
    if (item.value == data) {
      formAdd.filmAge = item.age
      formAdd.count = item.countAll
      formAdd.lacquerNumber = item.lacquerNumber
      formAdd.roofNumber = item.roofNumber
      formAdd.sunNumber = item.sunNumber
      formAdd.colorAlterationNumber = item.colorAlterationNumber
      filmName.value = item.name
      number4 = item.nameNumber
    }
  })
  getFilmList()
}
let formAddRef = ref(null)
let formAddRef1 = ref(null)
let formAddRef2 = ref(null)
// 添加按钮
const onSubmit = async (formEl) => {
  await formAddRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        if (!formAdd.storeId) {
          throw '请选择门店'
        }
        if (!formAdd.customerService) {
          throw '客服编号'
        }
        if (
          formAdd.lacquerNumber * 1 +
          formAdd.colorAlterationNumber * 1 +
          formAdd.roofNumber * 1 +
          formAdd.sunNumber * 1 >
          formAdd.count
        ) {
          throw '膜的次数和大于总次数请修改'
        } else {
          formAdd.filmType = formAdd.filmType
            .replace(/[()]/g, '')
            .replace(/[a-zA-Z]/g, '')
          formAdd.region = formAdd.region.replace(/[()]/g, '').replace(/[a-zA-Z]/g, '')
          let AllData = JSON.parse(JSON.stringify(formAdd))
          delete AllData.number1
          delete AllData.number2
          delete AllData.number3
          AllData.storeId = [AllData.storeId]
          const res = await storeInventoryAdd(AllData)
          ElMessage.success(res.data.message)
          const keys = Object.keys(formAdd)
          let obj = {}
          keys.forEach((item) => {
            obj[item] = ""
          })
          Object.assign(formAdd, obj)
        }
      } catch (error) {
        ElMessage.error(error)
      }

    } else {
      ElMessage.error('请补充完整信息')
    }
  })

}
const getNumberData = async () => {
  let page = {
    page: 1,
    size: 10000
  }
  let res = await numberList(page)
  optionsNumber1.value = res.data.res.map((item) => {
    return {
      label: item.code,
      value: item.id
    }
  })
  let res2 = await number2List(page)
  optionsNumber2.value = res2.data.res.map((item) => {
    return {
      label: item.code,
      value: item.id
    }
  })
  let res3 = await number3List(page)
  optionsNumber3.value = res3.data.res.map((item) => {
    return {
      label: item.code,
      value: item.id
    }
  })
}
let number1 = ''
let number2 = ''
let number3 = ''
let number4 = ''
const selectNumber = (data) => {
  optionsNumber1.value.forEach((item) => {
    if (item.value == data) {
      number1 = item.label
    }
  })
  getFilmList()
}
const selectNumber2 = (data) => {
  optionsNumber2.value.forEach((item) => {
    if (item.value == data) {
      number2 = item.label
    }
  })
  getFilmList()
}
const selectNumber3 = (data) => {
  optionsNumber3.value.forEach((item) => {
    if (item.value == data) {
      number3 = item.label
    }
  })
  getFilmList()
}
onMounted(() => {
  formAdd.customerService = JSON.parse(localStorage.getItem('userInfo')).number
  getStoreList()
  getNumberData()
})
defineExpose({ getStoreList })
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
}
.qualityAddBox {
  // display: flex;
  // justify-content: center;
}
.card {
  width: 100%;
  margin-bottom: 10px;
}
.card2 {
  width: 100%;
  margin-bottom: 10px;
}
</style>